package com.sniper.web.action.admin;

import com.sniper.model.AdminRight;
import com.sniper.utils.DataUtil;
import com.sniper.utils.FilesUtil;
import com.sniper.utils.PageUtil;
import com.sniper.utils.ValidateUtil;
import com.sniper.web.searchUtils.AdminGroupSearch;
import com.sniper.web.utils.ControllerUtils;
import com.sniper.web.utils.ParamsToHtml;
import com.sniper.web.utils.TreeZTreeUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("${adminPath}/admin-right")
public class AdminRightController extends AdminBaseController {

    private static List<String> targets = new ArrayList<>();

    static {
        targets.add("_self");
        targets.add("_blank");
    }

    /**
     * 存放整个系统的菜单
     */
    public String getTreeRightMap() {
        TreeZTreeUtil treeUtil = new TreeZTreeUtil();
        Map<String, Object> params = new HashMap<>();
        params.put("order", "sort asc");
        treeUtil.setAdminRights(adminRightService.query("select", params));
        treeUtil.initAll();
        return treeUtil.getTreeNodesAll();
    }

    @RequiresPermissions("admin:right:view")
    @RequestMapping("/")
    public String index(Map<String, Object> map, AdminGroupSearch search) {


        ParamsToHtml toHtml = new ParamsToHtml();
        toHtml.setSniperUrl("/admin-right/delete");
        Map<String, String> menu = new HashMap<>();

        menu.put("true", "是");
        menu.put("false", "否");

        toHtml.addMapValue("theMenu", menu);

        Map<String, String> show = new HashMap<>();

        show.put("true", "是");
        show.put("false", "否");
        toHtml.addMapValue("theShow", show);

        toHtml.addMapValue("type", RIGHT_TYPE);

        Map<String, String> keys = new HashMap<>();
        keys.put("theMenu", "是否是菜单");
        keys.put("theShow", "是否是显示");
        keys.put("type", "类型");

        toHtml.setKeys(keys);
        //
        map.put("sniperMenu", toHtml);

        Map<String, Object> params = new HashMap<>();
        if (ValidateUtil.isValid(search.getIsShow())) {
            params.put("show", search.getIsShow());
        }

        if (ValidateUtil.isValid(search.getIsMenu())) {
            params.put("menu", search.getIsMenu());
        }

        if (ValidateUtil.isValid(search.getType())) {
            params.put("type", search.getType());
        }

        if (ValidateUtil.isValid(search.getGroupName())) {
            params.put("name", "%" + search.getGroupName() + "%");
        }

        if (ValidateUtil.isValid(search.getUrl())) {
            params.put("url", "%" + search.getUrl() + "%");
        }

        if (ValidateUtil.isValid(search.getFid())) {
            params.put("fid", search.getFid());
        }

        params.put("order", "ctime desc");
        PageUtil page = adminRightService.page(request, search.getLimit(), params);
        page.setRequest(request);

        map.put("page", page);
        map.put("groupSearch", search);
        return forward("/admin/admin-right/index.jsp");
    }

    /**
     * 更新展示,修改展示
     *
     * @param map
     * @return
     */
    @RequiresPermissions("admin:right:insert")
    @RequestMapping(value = "insert", method = RequestMethod.GET)
    public String insert(Map<String, Object> map) {
        // 这是id未0,当id未0时,就是保存操作
        map.put("adminRight", new AdminRight());
        map.put("targets", targets);
        map.put("treeRightMap", getTreeRightMap());
        map.put("rightType", RIGHT_TYPE);
        return site.getName() + "/admin/admin-right/save-input.jsp";
    }

    /**
     * 数据插入 数据校验
     * <p>
     * 必须和BindingResult靠着
     *
     * @param adminRight
     * @param result
     * @return
     */
    @ResponseBody
    @RequiresPermissions("admin:right:insert")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public ControllerUtils.CallBackResult insert(@Validated AdminRight adminRight,
                                                 BindingResult result) {

        return new ControllerUtils().ajaxPostResult(result, callBackResult -> {
            adminRight.setId(FilesUtil.UUID());
            adminRightService.insert(adminRight);
            return callBackResult;
        });

    }

    /**
     * 更新展示,修改展示
     *
     * @param id
     * @param map
     * @return
     */
    @RequiresPermissions("admin:right:update")
    @RequestMapping(value = "update", method = RequestMethod.GET)
    public String update(
            @RequestParam(value = "id", required = false) String id,
            Map<String, Object> map, AdminRight adminRight) {

        if (ValidateUtil.isValid(id)) {
            adminRight = adminRightService.get(id);
        }

        if (adminRight == null) {
            return redirect("/admin-right/insert");
        }

        map.put("adminRight", adminRight);
        map.put("targets", targets);
        map.put("treeRightMap", getTreeRightMap());
        map.put("rightType", RIGHT_TYPE);
        return site.getName() + "/admin/admin-right/save-input.jsp";
    }

    @ResponseBody
    @RequiresPermissions("admin:right:update")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public ControllerUtils.CallBackResult update(@Validated AdminRight adminRight, BindingResult result) {

        return new ControllerUtils().ajaxPostResult(result, callBackResult -> {
            adminRightService.update(adminRight);
            return callBackResult;
        });
    }

    @RequiresPermissions("admin:right:delete")
    @ResponseBody
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public Map<String, Object> delete(@RequestParam("delid") String[] delid,
                                      @RequestParam("menuType") String menuType,
                                      @RequestParam("menuValue") String menuValue) {
        Map<String, Object> ajaxResult = new HashMap<>();
        switch (menuType) {
            case "delete":
                ControllerUtils.delete(ajaxResult, adminRightService, delid);
                break;
            case "theShow":
                try {
                    for (String string : delid) {
                        AdminRight adminRight = adminRightService.get(string);
                        adminRight.setTheShow(DataUtil.stringToBoolean(menuValue));
                        adminRightService.update(adminRight);
                    }

                    ajaxResult.put("code", 1);
                    ajaxResult.put("msg", "success");
                } catch (Exception e) {
                    ajaxResult.put("code", -1);
                    ajaxResult.put("msg", e.getMessage());
                }

                break;
            case "thePublic":

                try {
                    for (String string : delid) {
                        AdminRight adminRight = adminRightService.get(string);
                        adminRight
                                .setThePublic(DataUtil.stringToBoolean(menuValue));
                        adminRightService.update(adminRight);
                    }
                    ajaxResult.put("code", 1);
                    ajaxResult.put("msg", "success");
                } catch (Exception e) {
                    ajaxResult.put("code", -1);
                    ajaxResult.put("msg", e.getMessage());
                }

                break;
            case "theMenu":
                try {
                    for (String string : delid) {
                        AdminRight adminRight = adminRightService.get(string);
                        adminRight.setTheMenu(DataUtil.stringToBoolean(menuValue));
                        adminRightService.update(adminRight);
                    }
                    ajaxResult.put("code", 1);
                    ajaxResult.put("msg", "success");
                } catch (Exception e) {
                    ajaxResult.put("code", -1);
                    ajaxResult.put("msg", e.getMessage());
                }

                break;

            case "type":
                try {
                    for (String string : delid) {
                        AdminRight adminRight = adminRightService.get(string);
                        adminRight.setType(menuValue);
                        adminRightService.update(adminRight);
                    }
                    ajaxResult.put("code", 1);
                    ajaxResult.put("msg", "success");
                } catch (Exception e) {
                    ajaxResult.put("code", -1);
                    ajaxResult.put("msg", e.getMessage());
                }

                break;

            default:
                break;
        }

        return ajaxResult;
    }
}